package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExeptionHandler {

    // 数据库的约束错误信息，可能有很多：主键 唯一 非空约束 外键约束
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R  handlerSQLConstraintException(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage());
        String message = exception.getMessage();
        if(message.contains("Duplicate entry")){//违反的是唯一约束
            String username = message.split(" ")[2].replace("'", "");
            return R.error(username+" 已存在");
        }
        return R.error("数据异常！！");
    }

    //处理我们的自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public R handlerBusinessException(BusinessException exception){
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }
}
